<!-- （张仕琪）配送地址添加页面 -->
<template>
  <div>
    <van-nav-bar title="新增地址" placeholder fixed left-arrow @click-left="goBack" />

    <!-- <van-address-edit v-model="address" :area-list="areaList" show-set-default show-search-result area-placeholder
      :address-info="address" :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave" @change-detail="onChangeDetail">
      <van-field v-model="address.userGender" label="性别" placeholder="性别"></van-field>
    </van-address-edit> -->
    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field required v-model="address.userName" label="姓名" placeholder="姓名" />

        <van-field required v-model="address.userGender" label="性别" placeholder="男 / 女" />

        <van-field required v-model="address.userTel" type="tel" label="手机号" placeholder="手机号" />

        <van-field v-model="districtName" is-link readonly label="选择省市区" placeholder="选择省市区"
          @click="showDistrictPicker = true" />
        <van-popup v-model:show="showDistrictPicker" round position="bottom">
          <van-area title="选择省市区" :area-list="areaList" :value="address.userDistrict" @confirm="onDistrictConfirm"
            @cancel="showDistrictPicker = false" />
        </van-popup>

        <van-field required v-model="address.userAddress" label="详细地址" placeholder="详细地址" />
        
        <van-cell center title="设为默认收货地址">
          <template #right-icon>
            <van-switch v-model="checked" size="24" active-color="#ee0a24" inactive-color="#dcdee0" />
          </template>
        </van-cell>
      </van-cell-group>


      <div style="margin: 12px; ">
        <van-button block type="primary" round native-type="submit" color="linear-gradient(to right, #ff6034, #ee0a24)">
          <span style="font-size: 18px;">&nbsp; 提 &nbsp; 交 &nbsp;</span>
        </van-button>

      </div>

    </van-form>
  </div>
</template>

<script setup>

import { ref, reactive, defineProps } from 'vue';
import { Notify, Toast } from 'vant';
import { useRouter } from "vue-router";
import { areaList } from "@vant/area-data";
import { computed } from '@vue/reactivity';
import http from "@/utils/request.js";
import { deepCopy } from '@/utils/object.js';
import { getHeadImageUrl } from '@/utils/api.js'
//拿路由传的id
const props = defineProps(['userId']);
const showDistrictPicker = ref(false);
const searchResult = ref([]);
const goBack = () => history.back();
const checked = ref(false);


const address = reactive({
  userId: props.userId,
  userName: '',
  userGender: '',
  userTel: '',
  userProvince: '',
  userCity: '',
  userDistrict: '',
  userAddress: '',
  addressDefault: 0,
})


//确认选择省市区触发的事件
const onDistrictConfirm = function (areaValues) {
  console.log('onDistrictConfirm = ', areaValues);
  showDistrictPicker.value = false;
  address.userProvince = areaValues[0].name;
  address.userCity = areaValues[1].name;
  address.userDistrict = areaValues[2].name;
  console.log(address);
}
//当用户选择省市区之后，显示 省/市/区
const districtName = computed(() => {
  if (address.userDistrict) {
    return address.userProvince + '/' + address.userCity + '/' + address.userDistrict;
  } else {
    return '请选择 省/市/区';
  }
})


const onSubmit = function () {
  console.log('--提交地址--', address);
  http.post(
    "/address/addAddress",address
  ).then((res) =>{
    if(res.data.resCode === '200'){
      Notify({type: 'success',message: '添加成功！'})
      setTimeout(( )=>{
        history.back();
      },500);
    }
  })
}
// export default {
//   data() {
//     return {
//       areaList,
//       searchResult: [],
//       info: [],
//       uname: sessionStorage.getItem("uname"),
//     };
//   },
//   methods: {
//     goBack() {
//       this.$router.go(-1);
//     },
//     onSave(content) {
//       this.isDefault = content.isDefault ? "1" : "0"; //数据库该项设置为0，1，如不需修改可删除该行
//       //如果地址id不存在，则连接新增地址接口，存在则连接修改地址接口
//       if (!this.$route.query.id) {
//         //发送请求连接新增地址接口
//         this.axios
//           .post(
//             "/addAddress",
//             `uname=${this.uname}&name=${content.name}&phone=${content.tel}&province=${content.province}&city=${content.city}&county=${content.county}&detail_addr=${content.addressDetail}&group_message=${this.isDefault }&areaCode=${content.areaCode}&postalCode=${content.postalCode}`
//           )
//           .then((res) => {
//             console.log(res);
//           });
//       } else {
//         //发送请求连接修改地址接口
//         this.axios
//           .post(
//             "/updateAddress",
//             `id=${this.$route.query.id}&name=${content.name}&phone=${content.tel}&province=${content.province}&city=${content.city}&county=${content.county}&detail_addr=${content.addressDetail}&group_message=${this.group_message}&areaCode=${content.areaCode}&postalCode=${content.postalCode}`
//           )
//           .then((res) => {
//             console.log(res);
//           });
//       }
//       this.$toast.success("保存成功");
//       //返回地址列表页，强制刷新
//       this.$router.replace("/addresslist");
//       location.reload();
//     },
//     onDelete() {
//       let id = this.$route.query.id;
//       //发送请求连接删除地址接口
//       this.axios.post("/delAddress?id=" + id).then((res) => {
//         console.log(res.data);
//       });
//       this.$toast.success("删除成功");
//       this.$router.go(-1);
//     },
//   },
//   mounted() {
//     //获取地址列表传的地址id
//     let id = this.$route.query.id;
//     //地址id存在则发请求回显地址
//     if (id) {
//       //发送请求获取地址内容
//       this.axios.post("/addressId?id=" + id).then((res) => {
//         //通过address-info回显地址
//         this.info = res.data.results;
//         this.info.isDefault = this.info.isDefault == 1 ? true : false;
//         console.log(this.info.isDefault);
//         console.log(this.info);
//       });
//     }
//   },
// };

</script>

